package com.siruier.boss.ui.helper

import android.content.Context
import androidx.activity.ComponentActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner


typealias ILoa = ILifecycleOwnerActivity

fun loa(): LifecycleOwnerActivity = LifecycleOwnerActivity()

interface ILifecycleOwnerActivity {

    val mLoaContext: Context?

    val mLoaLifecycle: Lifecycle?

    val mLoaLifecycleOwner: LifecycleOwner?

    /**
     * 初始化
     */
    fun <Host : LifecycleOwner> Host.initLifecycleOwnerActivity()
}

class LifecycleOwnerActivity : ILifecycleOwnerActivity {
    private var loaContext: Context? = null
    private var mLifecycle: Lifecycle? = null
    private var mLifecycleOwner: LifecycleOwner? = null

    override val mLoaContext: Context?
        get() = loaContext

    override val mLoaLifecycle: Lifecycle?
        get() = mLifecycle

    override val mLoaLifecycleOwner: LifecycleOwner?
        get() = mLifecycleOwner

    override fun <Host : LifecycleOwner> Host.initLifecycleOwnerActivity() {
        when (this) {
            is ComponentActivity -> {
                loaContext = this
                mLifecycleOwner = this
            }
            is Fragment -> {
                loaContext = requireContext()
                mLifecycleOwner = this
            }
            else -> {
                throw IllegalArgumentException("ILifecycleOwnerActivity only support `ComponentActivity` and `Fragment`.")
            }
        }
        mLifecycle = lifecycle
        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                loaContext = null
                mLifecycle = null
            }
        })
    }
}